# admin/jira/jira_route.py

# 标准库
import json
import logging
from datetime import datetime

# 第三方库
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file
from flask_login import login_required, current_user
import pandas as pd

# 本地模块
from admin.admin.admin_config import system_config
from admin.wxwork.wxwork_sync import WeComSync
from inc.models import (
    db, JiraProject, JiraCategory, JiraLevel, JiraMember, JiraStage, JiraTask, JiraReview, AdminMember,
    Group, GroupUser, JiraApprovalFlow, SystemConfig, OperationLog
)

# 创建蓝图
jira_bp = Blueprint('jira', __name__, url_prefix='/admin/jira')

# 配置日志
logger = logging.getLogger('JiraManagement')


# Jira项目管理主页
@jira_bp.route('/')
@login_required
def project_list():
    status_filter = request.args.get('status', 'all')
    category_filter = request.args.get('category', 'all')

    # 构建查询
    query = JiraProject.query

    if status_filter != 'all':
        query = query.filter(JiraProject.status == status_filter)

    if category_filter != 'all' and category_filter != '0':
        query = query.filter(JiraProject.category_id == category_filter)

    # 分页
    page = request.args.get('page', 1, type=int)
    per_page = 10
    projects = query.order_by(JiraProject.created_at.desc()).paginate(page=page, per_page=per_page, error_out=False)

    categories = JiraCategory.query.all()

    system_config = SystemConfig.query.first()

    return render_template('admin/jira/jira_list.html',
                           projects=projects,
                           categories=categories,
                           status_filter=status_filter,
                           category_filter=category_filter,
                           system_config=system_config)


# 创建项目
@jira_bp.route('/create', methods=['GET', 'POST'])
@login_required
def create_project():
    if request.method == 'POST':
        try:
            # 获取表单数据
            name = request.form.get('name')
            description = request.form.get('description')
            category_id = request.form.get('category_id')
            level_id = request.form.get('level_id')
            reviewer_id = request.form.get('reviewer_id')
            member_ids = request.form.getlist('member_ids')
            start_date = request.form.get('start_date')
            end_date = request.form.get('end_date')

            # 验证必要字段
            if not name or not category_id or not level_id:  # 移除reviewer_id验证
                flash('请填写必要字段', 'danger')
                return redirect(url_for('jira.create_project'))

            current_user_id = getattr(current_user, 'id', 1)  # 默认为1，实际应用中应该确保用户已登录

            # 创建项目
            project = JiraProject(
                name=name,
                description=description,
                category_id=category_id,
                level_id=level_id,
                owner_id=current_user_id,
                first_approver_id=request.form.get('first_approver_id'),  # 新增指定审批人
                reviewer_id=request.form.get('first_approver_id'),  # 复用为结项审批人
                started_at=datetime.strptime(start_date, '%Y-%m-%d') if start_date else None
            )

            db.session.add(project)
            db.session.flush()  # 获取项目ID

            # 添加项目成员（包括创建者）
            all_member_ids = set()
            for mid in member_ids:
                try:
                    all_member_ids.add(int(mid))
                except ValueError:
                    logger.warning(f"无效的成员ID: {mid}")

            # 添加项目创建者作为成员
            all_member_ids.add(current_user_id)

            for user_id in all_member_ids:
                project_member = JiraMember(
                    project_id=project.id,
                    member_id=user_id
                )
                db.session.add(project_member)

            # 添加默认阶段
            default_stages = [
                ("项目启动", "定义项目目标、范围和关键利益相关者"),
                ("项目规划", "制定详细的项目计划、时间表和资源分配"),
                ("项目执行", "按照计划执行项目任务和活动"),
                ("项目监控", "跟踪项目进展、管理风险和变更"),
                ("项目收尾", "完成交付、总结经验并正式结束项目")
            ]

            for order, (name, desc) in enumerate(default_stages):
                stage = JiraStage(
                    project_id=project.id,
                    name=name,
                    description=desc,
                    order=order
                )
                db.session.add(stage)

            db.session.commit()
            flash('项目创建成功', 'success')
            return redirect(url_for('jira.project_detail', project_id=project.id))

        except Exception as e:
            db.session.rollback()
            logger.error(f"创建项目失败: {str(e)}")
            flash(f'创建项目失败: {str(e)}', 'danger')

    # GET请求
    categories = JiraCategory.query.all()
    levels = JiraLevel.query.all()
    members = AdminMember.query.filter(AdminMember.status == True).all()
    flows = JiraApprovalFlow.query.all()  #  取所有审批流程

    # 过滤出有审批权限的成员
    approvers = [m for m in members if m.has_permission('REVIEW_PROJECT')]
    return render_template('admin/jira/jira_create.html',
                           categories=categories,
                           levels=levels,
                           users=members,
                           approvers=approvers,  # 新增审批人列表
                           flows=flows)


# 获取项目详情
@jira_bp.route('/<int:project_id>')
@login_required
def project_detail(project_id):
    project = JiraProject.query.get_or_404(project_id)
    if project.started_at is None:
        project.started_at = datetime.now()  # 或其他默认值
    if project.status == JiraProject.COMPLETED and project.closure_reviewed_at is None:
        project.closure_reviewed_at = datetime.now()  # 或其他默认值
    return render_template('admin/jira/jira_detail.html', project=project)

@jira_bp.route('/<int:project_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_project(project_id):
    """编辑项目"""
    project = JiraProject.query.get_or_404(project_id)

    # 权限检查：只有项目负责人或管理员可以编辑（管理员可以编辑任何状态的项目）
    if project.owner_id != current_user.id and not current_user.is_admin:
        flash('只有项目负责人或管理员可以编辑项目', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    if request.method == 'POST':
        try:
            # 更新项目基本信息
            project.name = request.form.get('name')
            project.description = request.form.get('description')
            project.category_id = request.form.get('category_id')
            project.level_id = request.form.get('level_id')
            project.first_approver_id = request.form.get('first_approver_id')  # 新增
            project.reviewer_id = request.form.get('first_approver_id')  # 复用为结项审批人
            project.start_date = datetime.strptime(request.form.get('start_date'), '%Y-%m-%d') if request.form.get('start_date') else None
            project.end_date = datetime.strptime(request.form.get('end_date'), '%Y-%m-%d') if request.form.get('end_date') else None
            project.approval_flow_id = request.form.get('approval_flow_id')

            # 更新成员 - 确保owner_id始终在成员表中
            member_ids = set(request.form.getlist('member_ids'))
            member_ids.add(str(project.owner_id))  # 确保owner_id在成员列表中

            # 先删除非owner的现有成员
            JiraMember.query.filter(
                JiraMember.project_id == project.id,
                JiraMember.member_id != project.owner_id
            ).delete()

            # 添加新成员(排除已存在的owner)
            existing_members = {str(m.member_id) for m in project.members}
            for user_id in member_ids:
                if user_id not in existing_members:
                    db.session.add(JiraMember(
                        project_id=project.id,
                        member_id=user_id
                    ))

            db.session.commit()
            flash('项目更新成功', 'success')
            return redirect(url_for('jira.project_detail', project_id=project.id))
        except Exception as e:
            db.session.rollback()
            logger.error(f"更新项目失败: {str(e)}")
            flash(f'更新项目失败: {str(e)}', 'danger')

    # GET请求
    categories = JiraCategory.query.all()
    levels = JiraLevel.query.all()
    members = AdminMember.query.filter(AdminMember.status == True).all()
    flows = JiraApprovalFlow.query.all()

    # 过滤出有审批权限的成员
    approvers = [m for m in members if m.has_permission('REVIEW_PROJECT')]
    return render_template('admin/jira/jira_edit.html',
                         project=project,
                         categories=categories,
                         levels=levels,
                         users=members,
                         approvers=approvers,  # 新增审批人列表
                         flows=flows)

# 提交审核
@jira_bp.route('/<int:project_id>/submit', methods=['POST'])
@login_required  # 添加登录要求
def submit_project(project_id):
    project = JiraProject.query.get_or_404(project_id)

    # 提交审核
    if project.owner_id != current_user.id:
         flash('只有项目负责人可以提交审核', 'danger')
         return redirect(url_for('jira.project_detail', project_id=project_id))

    # 状态检查：只有草稿状态的项目可以提交
    if project.status != JiraProject.DRAFT:
        flash('只有草稿状态的项目可以提交审核', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 更新项目状态
    project.status = JiraProject.PENDING
    project.submitted_at = datetime.now()
    # 确保项目创建人仍然是成员
    if not JiraMember.query.filter_by(project_id=project.id, member_id=project.owner_id).first():
        db.session.add(JiraMember(
            project_id=project.id,
            member_id=project.owner_id
        ))
    db.session.commit()

    flash('项目已提交审核', 'success')
    return redirect(url_for('jira.project_detail', project_id=project_id))


# 审核项目
@jira_bp.route('/<int:project_id>/review', methods=['POST'])
@login_required
def review_project(project_id):
    project = JiraProject.query.get_or_404(project_id)

    # 状态检查：只有待审核状态的项目可以审核
    if project.status != JiraProject.PENDING:
        flash('项目不在待审核状态', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 获取当前审核步骤
    current_step = project.current_approval_step
    if not project.approval_flow or current_step > len(project.approval_flow.steps):
        flash('项目没有配置有效的审核流程', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 获取审核结果
    action = request.form.get('action')
    review_notes = request.form.get('review_notes', '')

    if action == 'approve':
        # 如果是最后一步审核，则批准项目
        if current_step == len(project.approval_flow.steps):
            project.status = JiraProject.APPROVED
            project.current_approval_step = current_step + 1

            # 自动创建企业微信群
            try:
                member_wecom_ids = [
                    m.member.wecom_userid
                    for m in project.members
                    if m.member and hasattr(m.member, 'wecom_userid') and m.member.wecom_userid
                ]
                owner_wecom_id = project.owner.wecom_userid if project.owner and hasattr(project.owner, 'wecom_userid') else None

                if owner_wecom_id and member_wecom_ids:
                    chat_id = WeComSync.create_app_chat(
                        name=f"项目-{project.name}",
                        owner=owner_wecom_id,
                        userlist=member_wecom_ids
                    )
                    if chat_id:
                        group = Group(
                            name=f"项目-{project.name}",
                            chat_id=chat_id,
                            owner_id=project.owner_id,
                            status=Group.ACTIVE,
                            assigned_tags=f"项目,{project.name}"
                        )
                        db.session.add(group)
                        db.session.flush()
                        project.group_id = group.id
                        for member in project.members:
                            db.session.add(GroupUser(
                                group_id=group.id,
                                user_id=member.member_id,
                                status=GroupUser.ACTIVE
                            ))
                        flash('项目已批准，并成功创建企业微信群', 'success')
                    else:
                        flash('项目已批准，但创建企业微信群失败', 'warning')
                else:
                    flash('项目已批准，但缺少有效的企业微信ID', 'warning')
            except Exception as e:
                logger.error(f"创建企业微信群失败: {str(e)}")
                flash('项目已批准，但创建企业微信群时发生错误', 'warning')
        else:
            # 否则进入下一步审核
            project.current_approval_step = current_step + 1
            flash(f'项目已通过第{current_step}步审核', 'success')
    elif action == 'reject':
        project.status = JiraProject.REJECTED
        flash('项目已拒绝', 'success')
    else:
        flash('无效的操作', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 保存审核记录
    project.reviewed_at = datetime.now()
    project.review_notes = review_notes

    # 添加审核历史记录
    review = JiraReview(
        project_id=project.id,
        reviewer_id=current_user.id,
        node_id=current_step,
        status=project.status,
        notes=review_notes
    )
    db.session.add(review)

    db.session.commit()
    return redirect(url_for('jira.project_detail', project_id=project_id))


# 开始项目
@jira_bp.route('/<int:project_id>/start', methods=['GET', 'POST'])
@login_required
def start_project(project_id):
    project = JiraProject.query.get_or_404(project_id)

    # 开始项目
    if project.owner_id != current_user.id:
         flash('只有项目负责人可以开始项目', 'danger')
         return redirect(url_for('jira.project_detail', project_id=project_id))

    # 状态检查：只有已批准的项目可以开始
    if project.status != JiraProject.APPROVED:
        flash('只有已批准的项目可以开始', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 更新项目状态
    project.status = JiraProject.IN_PROGRESS
    db.session.commit()

    flash('项目已开始', 'success')
    return redirect(url_for('jira.project_detail', project_id=project_id))


# 任务分配表单
@jira_bp.route('/task/<int:task_id>/assign_form')
@login_required
def assign_task_form(task_id):
    task = JiraTask.query.get_or_404(task_id)
    project = task.stage.project
    if current_user.id != project.owner_id:
        flash('只有项目负责人可以分配任务', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project.id))

    return render_template('admin/jira/task_assign.html',
                         task=task,
                         project=project)


# 创建任务
@jira_bp.route('/task/create/<int:stage_id>', methods=['GET', 'POST'])
@login_required
def create_task(stage_id):
    stage = JiraStage.query.get_or_404(stage_id)
    project = stage.project

    # 权限检查：只有项目负责人或管理员可以创建任务
    if project.owner_id != current_user.id and not current_user.is_admin:
        flash('只有项目负责人或管理员可以创建任务', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project.id))

    if request.method == 'POST':
        try:
            # 获取表单数据
            name = request.form.get('name')
            description = request.form.get('description')
            assignee_id = request.form.get('assignee_id')
            due_date = request.form.get('due_date')

            if not name:
                flash('请填写任务名称', 'danger')
                return redirect(url_for('jira.create_task', stage_id=stage.id))

            # Validate assignee_id
            assignee_id = request.form.get('assignee_id')
            if assignee_id:
                try:
                    assignee_id = int(assignee_id)
                except ValueError:
                    flash('无效的任务负责人ID，请选择有效的成员', 'danger')
                    return redirect(url_for('jira.create_task', stage_id=stage.id))
            else:
                assignee_id = None

            # Validate due_date
            due_date = request.form.get('due_date')
            if due_date:
                try:
                    due_date = datetime.strptime(due_date, '%Y-%m-%d')
                except ValueError:
                    flash('无效的截止日期，请输入正确的日期格式 (YYYY-MM-DD)', 'danger')
                    return redirect(url_for('jira.create_task', stage_id=stage.id))
            else:
                due_date = None

            # Create task
            task = JiraTask(
                name=name,
                description=description,
                stage_id=stage.id
            )
            db.session.add(task)
            db.session.commit()
            flash('任务创建成功', 'success')
            return redirect(url_for('jira.project_detail', project_id=project.id))
        except Exception as e:
            db.session.rollback()
            logger.error(f"创建任务失败: {str(e)}")
            flash(f'创建任务失败: {str(e)}', 'danger')

    # GET请求：渲染创建任务表单
    members = AdminMember.query.filter_by(status=True).all()
    return render_template('admin/jira/task_create.html',
                         stage=stage,
                         members=members)

# 任务分配提交
@jira_bp.route('/task/<int:task_id>/assign', methods=['POST'])
@login_required
def assign_task(task_id):
    task = JiraTask.query.get_or_404(task_id)
    project = task.stage.project
    if current_user.id != project.owner_id and not current_user.is_admin:
        flash('只有项目负责人可以分配任务', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project.id))

    member_id = request.form.get('member_id')
    if not member_id:
        flash('请选择成员', 'danger')
        return redirect(url_for('jira.assign_task_form', task_id=task.id))

    task.assignee_id = member_id
    db.session.commit()
    flash('任务已成功分配', 'success')
    return redirect(url_for('jira.project_detail', project_id=project.id))

# 任务评价表单
@jira_bp.route('/task/<int:task_id>/rate_form')
@login_required
def rate_task_form(task_id):
    task = JiraTask.query.get_or_404(task_id)
    project = task.stage.project
    if current_user.id != project.owner_id:
        flash('只有项目负责人可以评价任务', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project.id))

    return render_template('admin/jira/task_rate.html',
                         task=task,
                         project=project)

# 任务评价提交
@jira_bp.route('/task/<int:task_id>/rate', methods=['POST'])
@login_required
def rate_task(task_id):
    task = JiraTask.query.get_or_404(task_id)
    project = task.stage.project
    if current_user.id != project.owner_id:
        flash('只有项目负责人可以评价任务', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project.id))

    rating = request.form.get('rating')
    feedback = request.form.get('feedback', '')

    if not rating:
        flash('请选择评分', 'danger')
        return redirect(url_for('jira.rate_task_form', task_id=task.id))

    task.rating = int(rating)
    task.feedback = feedback
    db.session.commit()

    flash('任务评价已保存', 'success')
    return redirect(url_for('jira.project_detail', project_id=project.id))

# 完成任务
@jira_bp.route('/task/<int:task_id>/complete', methods=['POST'])
@login_required
def complete_task(task_id):
    task = JiraTask.query.get_or_404(task_id)

    # 完成任务
    if task.assignee_id != current_user.id:
         flash('只有任务负责人可以完成任务', 'danger')
         return redirect(url_for('jira.project_detail', project_id=task.stage.project_id))

    # 更新任务状态
    task.status = JiraTask.DONE
    task.completed_at = datetime.now()
    db.session.commit()

    flash('任务已完成', 'success')
    return redirect(url_for('jira.project_detail', project_id=task.stage.project_id))


# 项目评分
@jira_bp.route('/<int:project_id>/score', methods=['POST'])
@login_required
def score_project(project_id):
    project = JiraProject.query.get_or_404(project_id)

    # 项目评分
    if project.owner_id != current_user.id:
         flash('只有项目负责人可以评分', 'danger')
         return redirect(url_for('jira.project_detail', project_id=project_id))

    # 状态检查：只有已完成的项目可以评分
    if project.status != JiraProject.COMPLETED:
        flash('只有已完成的项目可以评分', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 处理评分
    for member in project.members:
        score_key = f"score_{member.user_id}"
        notes_key = f"notes_{member.user_id}"

        if score_key in request.form:
            try:
                score = float(request.form[score_key])
                if 0 <= score <= 100:  # 假设评分范围是0-100
                    member.score = score
                    member.score_notes = request.form.get(notes_key, '')
            except ValueError:
                pass  # 忽略无效的分数

    db.session.commit()
    flash('评分已保存', 'success')
    return redirect(url_for('jira.project_detail', project_id=project_id))


# 完成项目
@jira_bp.route('/<int:project_id>/delete', methods=['POST'])
@login_required
def delete_project(project_id):
    """删除项目"""
    project = JiraProject.query.get_or_404(project_id)

    # 权限检查：只有项目负责人或管理员可以删除（管理员可以删除任何状态的项目）
    if project.owner_id != current_user.id and not current_user.is_admin:
        flash('只有项目负责人或管理员可以删除项目', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    try:
        # 删除相关数据
        JiraMember.query.filter_by(project_id=project.id).delete()

        # 先删除所有任务附件
        from inc.models import TaskAttachment
        task_ids = [t.id for stage in project.stages for t in stage.tasks]
        TaskAttachment.query.filter(TaskAttachment.task_id.in_(task_ids)).delete()
        logger.info(f"已删除项目 {project.id} 下的所有任务附件")

        # 删除阶段（级联删除会自动处理关联的任务）
        stages = project.stages
        logger.info(f"准备删除项目 {project.id} 下的 {len(stages)} 个阶段")

        # 直接删除阶段，依赖级联删除处理任务
        stage_count = JiraStage.query.filter_by(project_id=project.id).delete()
        logger.info(f"已删除项目 {project.id} 下的 {stage_count} 个阶段")

        # 删除评审记录
        review_count = JiraReview.query.filter_by(project_id=project.id).delete()
        logger.info(f"已删除项目 {project.id} 下的 {review_count} 条评审记录")

        # 删除项目
        db.session.delete(project)
        db.session.commit()

        flash('项目已成功删除', 'success')
        return redirect(url_for('jira.project_list'))
    except Exception as e:
        db.session.rollback()
        logger.error(f"删除项目失败: {str(e)}")
        flash(f'删除项目失败: {str(e)}', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

@jira_bp.route('/<int:project_id>/complete', methods=['POST'])
@login_required
def complete_project(project_id):
    project = JiraProject.query.get_or_404(project_id)

    # 完成项目
    if project.owner_id != current_user.id:
        flash('只有项目负责人可以完成项目', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 状态检查：只有进行中的项目可以完成
    if project.status != JiraProject.IN_PROGRESS:
        flash('只有进行中的项目可以完成', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 检查所有阶段是否完成
    incomplete_stages = any(stage.status != JiraStage.COMPLETED for stage in project.stages)
    if incomplete_stages:
        flash('还有未完成的阶段，无法完成项目', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 检查所有任务是否已完成
    for stage in project.stages:
        for task in stage.tasks:
            if task.status != JiraTask.COMPLETED:
                flash('还有未完成的任务，无法完成项目', 'danger')
                return redirect(url_for('jira.project_detail', project_id=project_id))

    # 请求项目结项（进入结项审核流程）
    from member.workflow.services import ProjectWorkflow
    try:
        ProjectWorkflow.request_project_closure(project_id, current_user.id)
        flash('项目已提交结项申请，等待第一审批人审核', 'success')
    except Exception as e:
        db.session.rollback()
        flash(f'提交结项申请失败: {str(e)}', 'danger')
        logger.error(f'提交结项申请失败: {str(e)}')

    return redirect(url_for('jira.project_detail', project_id=project_id))


# 类别管理
@jira_bp.route('/categories', methods=['GET', 'POST'])
@login_required
def manage_categories():
    # 管理类别

    if request.method == 'POST':
        name = request.form.get('name')
        description = request.form.get('description')

        if name:
            category = JiraCategory(name=name, description=description)
            db.session.add(category)
            db.session.commit()
            flash('类别添加成功', 'success')
        return redirect(url_for('jira.manage_categories'))

    system_config = SystemConfig.query.first()

    categories = JiraCategory.query.all()
    return render_template('admin/jira/jira_type.html', categories=categories, system_config=system_config)


# 级别管理
@jira_bp.route('/levels', methods=['GET', 'POST'])
@login_required
def manage_levels():
    # 管理级别

    if request.method == 'POST':
        name = request.form.get('name')
        priority = request.form.get('priority', 0, type=int)
        color = request.form.get('color', '#007bff')

        if name:
            level = JiraLevel(name=name, priority=priority, color=color)
            db.session.add(level)
            db.session.commit()
            flash('级别添加成功', 'success')
        return redirect(url_for('jira.manage_levels'))

    levels = JiraLevel.query.all()
    return render_template('admin/jira/jira_levels.html', levels=levels)


@jira_bp.route('/<int:project_id>/evaluate', methods=['POST'])
@login_required
def evaluate_project(project_id):
    """项目评价"""
    project = JiraProject.query.get_or_404(project_id)

    if request.method == 'POST':
        try:
            # 保存项目整体评价
            project.overall_rating = request.form.get('overall_rating')
            project.lessons_learned = request.form.get('lessons_learned')
            project.success_factors = request.form.get('success_factors')
            db.session.commit()
            flash('项目评价已保存', 'success')
        except Exception as e:
            db.session.rollback()
            flash(f'保存评价失败: {str(e)}', 'danger')

    return redirect(url_for('jira.project_detail', project_id=project_id))

@jira_bp.route('/<int:project_id>/review_closure', methods=['POST'])
@login_required
def review_closure(project_id):
    """结项审批"""
    project = JiraProject.query.get_or_404(project_id)
    reviewer = current_user.member if hasattr(current_user, 'member') else None

    if not reviewer:
        flash('无法识别审批人身份', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 检查用户是否有审批权限
    if reviewer.id != project.reviewer_id:
        flash('您不是此项目的审批人', 'danger')
        return redirect(url_for('jira.project_detail', project_id=project_id))

    # 获取审批结果
    action = request.form.get('action')
    notes = request.form.get('notes', '')
    score = request.form.get('score', type=float)

    if action == 'approve':
        if score is None:
            flash('请提供结项评分', 'danger')
            return redirect(url_for('jira.project_detail', project_id=project_id))

        project.approve_closure(reviewer.id, notes, score)
        flash('项目已成功结项', 'success')
    elif action == 'reject':
        project.reject_closure(reviewer.id, notes)
        flash('结项申请已被拒绝', 'warning')
    else:
        flash('无效的操作', 'danger')

    # 记录操作日志
    OperationLog.create(
        admin_id=current_user.id,
        action=f"结项审批-{'通过' if action == 'approve' else '拒绝'}",
        resource=f"Project-{project_id}",
        details=f"审批人 {reviewer.name} {'通过' if action == 'approve' else '拒绝'}了项目 {project.name} 的结项申请",
        success=True,
        ip_address=request.remote_addr
    )

    return redirect(url_for('jira.project_detail', project_id=project_id))


@jira_bp.route('/export', methods=['GET'])
@login_required
def export_projects():
    """导出项目数据为Excel"""
    from io import BytesIO

    # 获取项目数据
    projects = JiraProject.query.all()
    data = [{
        '项目名称': p.name,
        '状态': p.status,
        '负责人': p.owner.username,
        '开始时间': p.start_date,
        '结束时间': p.end_date,
        '进度': f"{p.completion_rate}%"
    } for p in projects]

    # 创建Excel文件
    output = BytesIO()
    pd.DataFrame(data).to_excel(output, index=False, engine='openpyxl')
    output.seek(0)

    return send_file(
        output,
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        as_attachment=True,
        download_name='项目列表.xlsx'
    )


@jira_bp.route('/task/management')
@login_required
def task_management():
    """任务管理后台"""
    if not current_user.is_admin and not current_user.has_permission('MANAGE_TASKS'):
        flash('您没有权限访问任务管理后台', 'danger')
        return redirect(url_for('jira.project_list'))

    # 获取所有项目及其任务
    projects = JiraProject.query.options(
        db.joinedload(JiraProject.stages)
        .joinedload(JiraStage.tasks)
        .joinedload(JiraTask.assignee)
    ).all()

    return render_template('admin/jira/task_management.html',
                         projects=projects)

@jira_bp.route('/task/bulk_assign', methods=['POST'])
@login_required
def bulk_assign_tasks():
    """批量分配任务"""
    if not current_user.is_admin and not current_user.has_permission('MANAGE_TASKS'):
        flash('您没有权限批量分配任务', 'danger')
        return redirect(url_for('jira.project_list'))

    task_ids = request.form.getlist('task_ids')
    assignee_id = request.form.get('assignee_id')

    if not task_ids or not assignee_id:
        flash('请选择任务和分配人', 'danger')
        return redirect(url_for('jira.task_management'))

    # 批量分配任务
    tasks = JiraTask.query.filter(JiraTask.id.in_(task_ids)).all()
    for task in tasks:
        task.assignee_id = assignee_id

    db.session.commit()
    flash(f'已成功分配{len(tasks)}个任务', 'success')
    return redirect(url_for('jira.task_management'))

@jira_bp.route('/archived')
@login_required
def archived_project_list():
    """已归档项目列表"""
    status_filter = request.args.get('status', 'all')
    category_filter = request.args.get('category', 'all')

    # 构建查询
    query = JiraProject.query.filter(JiraProject.is_archived == True)

    if status_filter != 'all':
        query = query.filter(JiraProject.status == status_filter)

    if category_filter != 'all' and category_filter != '0':
        query = query.filter(JiraProject.category_id == category_filter)

    # 分页
    page = request.args.get('page', 1, type=int)
    per_page = 10
    projects = query.order_by(JiraProject.archived_at.desc()).paginate(page=page, per_page=per_page, error_out=False)

    categories = JiraCategory.query.all()

    return render_template('admin/jira/archived_list.html',
                           projects=projects,
                           categories=categories,
                           status_filter=status_filter,
                           category_filter=category_filter)



# 保留项目创建时选择审批流程的最小功能
@jira_bp.route('/flows')
@login_required
def get_approval_flows():
    """获取审批流程列表(仅用于项目创建时选择)"""
    flows = JiraApprovalFlow.query.options(
        db.joinedload(JiraApprovalFlow.department)
    ).order_by(JiraApprovalFlow.is_default.desc(), JiraApprovalFlow.name).all()

    return jsonify([{
        'id': flow.id,
        'name': flow.name,
        'department': flow.department.name if flow.department else None
    } for flow in flows])


@jira_bp.route('/stats')
@login_required
def project_stats():
    total = JiraProject.query.count()
    in_progress = JiraProject.query.filter_by(status=JiraProject.IN_PROGRESS).count()
    completed = JiraProject.query.filter_by(status=JiraProject.COMPLETED).count()
    tasks_total = JiraTask.query.count()
    tasks_completed = JiraTask.query.filter_by(status=JiraTask.COMPLETED).count()
    members_total = JiraMember.query.distinct(JiraMember.member_id).count()

    stats = {
        'projects': {
            'total': total,
            'in_progress': in_progress,
            'completed': completed
        },
        'tasks': {
            'total': tasks_total,
            'completed': tasks_completed,
            'completion_rate': round((tasks_completed / tasks_total * 100), 2) if tasks_total > 0 else 0
        },
        'members': {
            'total': members_total
        }
    }

    return render_template('admin/jira/stats.html',
                         stats=stats,
                         stats_json=json.dumps(stats, indent=4, ensure_ascii=False))

# 添加级别
@jira_bp.route('/level/add', methods=['POST'])
@login_required
def add_level():
    name = request.form.get('name')
    priority = request.form.get('priority', 0, type=int)
    color = request.form.get('color', '#007bff')

    if not name:
        flash('请填写级别名称', 'danger')
        return redirect(url_for('jira.manage_levels'))

    level = JiraLevel(name=name, priority=priority, color=color)
    db.session.add(level)
    db.session.commit()

    flash('级别添加成功', 'success')
    return redirect(url_for('jira.manage_levels'))

# 编辑级别
@jira_bp.route('/level/edit', methods=['POST'])
@login_required
def edit_level():
    level_id = request.form.get('id')
    name = request.form.get('name')
    priority = request.form.get('priority', 0, type=int)
    color = request.form.get('color', '#007bff')

    level = JiraLevel.query.get_or_404(level_id)
    level.name = name
    level.priority = priority
    level.color = color
    db.session.commit()

    flash('级别更新成功', 'success')
    return redirect(url_for('jira.manage_levels'))

# 删除级别
@jira_bp.route('/level/<int:level_id>/delete', methods=['POST'])
@login_required
def delete_level(level_id):
    level = JiraLevel.query.get_or_404(level_id)

    # 检查是否有项目使用此级别
    if JiraProject.query.filter_by(level_id=level_id).count() > 0:
        flash('无法删除，已有项目使用此级别', 'danger')
        return redirect(url_for('jira.manage_levels'))

    db.session.delete(level)
    db.session.commit()

    flash('级别已删除', 'success')
    return redirect(url_for('jira.manage_levels'))

# 添加类别
@jira_bp.route('/category/add', methods=['POST'])
@login_required
def add_category():
    name = request.form.get('name')
    description = request.form.get('description')

    if not name:
        flash('请填写类别名称', 'danger')
        return redirect(url_for('jira.manage_categories'))

    category = JiraCategory(name=name, description=description)
    db.session.add(category)
    db.session.commit()

    flash('类别添加成功', 'success')
    return redirect(url_for('jira.manage_categories'))

# 编辑类别
@jira_bp.route('/category/edit', methods=['POST'])
@login_required
def edit_category():
    category_id = request.form.get('id')
    name = request.form.get('name')
    description = request.form.get('description')

    category = JiraCategory.query.get_or_404(category_id)
    category.name = name
    category.description = description
    db.session.commit()

    flash('类别更新成功', 'success')
    return redirect(url_for('jira.manage_categories'))

# 删除类别
@jira_bp.route('/category/<int:category_id>/delete', methods=['POST'])
@login_required
def delete_category(category_id):
    category = JiraCategory.query.get_or_404(category_id)

    # 检查是否有项目使用此类别
    if JiraProject.query.filter_by(category_id=category_id).count() > 0:
        flash('无法删除，已有项目使用此类别', 'danger')
        return redirect(url_for('jira.manage_categories'))

    db.session.delete(category)
    db.session.commit()

    flash('类别已删除', 'success')
    return redirect(url_for('jira.manage_categories'))
